<template>
<div class="login">
  <van-nav-bar
  title="登录页"
  ></van-nav-bar>
  <van-cell-group>
    <van-field
      v-model.trim="userInfo.mobile"
      required
      label="手机号"
      placeholder="请输入手机号"
      :error-message="mobellErr"
    />
    <van-field
      v-model.trim="userInfo.code"
      required
      label="密码"
      :placeholder="codeErr"
    />
  </van-cell-group>
  <div class="btn-warp">
    <van-button round type="info" class="btn" @click="hLogin">用户登录</van-button>
     <van-button round type="info" class="btn" @click="hTest">获取个人信息</van-button>
    当前是否登陆？{{ $store.state.tokenInfo.token ? '已登录' : '未登录' }}
  </div>
</div>
</template>
<script>
import { login, getProfile } from '@/api/user.js'
export default {
  name: 'Login',
  data () {
    return {
      userInfo: {
        mobile: '13912345678',
        code: '246810'
      },
      mobellErr: '',
      codeErr: ''
    }
  },
  methods: {
    /**
    * 1.表单验证
    */
    hTest () {
      getProfile()
    },
    validtor () {
      this.mobileErrMsg = /\d{11}/.test(this.userInfo.mobile) ? '' : '手机号不对'
      this.codeErrMsg = /\d{6}/.test(this.userInfo.code) ? '' : '密码不对'
      return (this.mobellErr === '' && this.codeErr === '')
    },
    /**
     * 2.发送请求
     */
    async hLogin () {
      if (!this.validtor()) {
        return
      }
      const { mobile, code } = this.userInfo
      // console.log(mobile, code)
      this.$toast.loading({
        duration: 0, // 持续展示 toast,永远不会关闭
        overlay: true, // 整体添加一个遮罩
        message: '加载中...'
      })
      try {
        const res = await login(mobile, code)
        console.log(res)
        this.$store.commit('mSetToken', res.data.data)
        console.log(res.data.data)
        this.$toast.success('登陆成功')
        console.log(1)
        this.$router.push('/')
      } catch (err) {
        console.log(err)
        this.$toast.fail('登陆失败')
      }
    }
  }
}
</script>
<style lang='less'>
.login {

  .btn-warp {
    .btn{
      width: 100%;
      background-color: #6db4fd;
      color:#fff;
    };
  }
}
</style>
